package cn.yunhe.insurance.controller;


import cn.yunhe.insurance.entity.Case;
import cn.yunhe.insurance.service.CaseService;
import cn.yunhe.insurance.util.DateUtil;
import cn.yunhe.insurance.util.UUIDGenerator;
import com.github.pagehelper.Page;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 案件控制器
 */
@RequestMapping("/case")
@RestController
public class CaseController {
    @Resource
    private CaseService caseService;

    public CaseService getCaseService() {
        return caseService;
    }

    public void setCaseService(CaseService caseService) {
        this.caseService = caseService;
    }

    @RequestMapping("/case")
    public ModelAndView toCase() {
        return new ModelAndView("caseList");
    }

    @RequestMapping("/toAddCase")
    public ModelAndView toAddCase() {
        return new ModelAndView("addCase");
    }

    /**
     * 案件信息列表
     *
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @RequestMapping("/caseList")
    public Map<String, Object> toCaseList(Integer pageNum, Integer pageSize, String keyword) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("keyword", keyword);
        Page page = caseService.getLikeCaseListByPage(map);
        map.put("page", page);
        map.put("totalPages", page.getPages());
        return map;
    }

    /**
     * 不同状态的案件信息列表
     *
     * @param pageNum
     * @param pageSize
     * @param caseState
     * @return
     */
    @RequestMapping("/caseStateList")
    public Map<String, Object> toCaseStateList(Integer pageNum, Integer pageSize, String caseState) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("caseState", Integer.parseInt(caseState));
        Page page = caseService.getPageCaseListByCaseState(map);
        map.put("page", page);
        map.put("totalPages", page.getPages());
        return map;
    }

    /**
     * 弹出修改页面
     *
     * @param caseUuid
     * @return
     */
    @RequestMapping("/toUpdateCase")
    public ModelAndView toUpdateCase(String caseUuid) {
        ModelAndView mv = new ModelAndView();
        Case cases = caseService.getCaseInfoByCaseUuid(caseUuid);
        mv.addObject("cases", cases);
        System.out.println(cases.getPayAccount());
        mv.setViewName("updateCase");
        return mv;
    }

    /**
     * 新增
     *
     * @param cases
     * @return
     */
    @RequestMapping("/addCase")
    public ModelAndView addCase(Case cases) {
        ModelAndView mv = new ModelAndView();
        String remarks=cases.getRemarks();
        if(remarks.length()>500){
        cases.setRemarks(remarks.substring(0,500));
        }
        cases.setCaseUuid(UUIDGenerator.getUUID());
        cases.setCaseId("C" + DateUtil.date2StringDateNo_(new Date()) + Calendar.getInstance().getTimeInMillis());
        boolean flag = caseService.addCase(cases);
        if (flag) {
            mv.setViewName("caseList");
        }
        return mv;
    }

    /**
     * 修改
     *
     * @param cases
     * @return
     */
    @RequestMapping("/updateCase")
    public Boolean updateCase(Case cases) {
        Boolean flag = caseService.updateCase(cases);
        return flag;
    }

    /**
     * 提交
     *
     * @param caseUuid
     * @return
     */
    @RequestMapping("/submit")
    public Boolean updateCaseStateTo0(String caseUuid) {
        Boolean flag = caseService.updateCaseStateTo0(caseUuid);
        return flag;
    }

    /**
     * 删除
     *
     * @param cases
     * @return
     */
    @RequestMapping("/del")
    public Boolean delCase(Case cases) {
        Boolean flag = caseService.delCase(cases);
        return flag;
    }

    /**
     * 弹出上传页面
     *
     * @param caseId
     * @return
     */
    @RequestMapping("/toUpload")
    public ModelAndView toUpload(String caseId) {
        ModelAndView mv = new ModelAndView("uploadCaseInfo");
        mv.addObject("caseId", caseId);
        return mv;
    }

    /**
     * 文件上传
     *
     * @param files
     * @param request
     * @param caseId
     * @return
     */
    @RequestMapping("upload")
    public Map<String, Object> upLoadFiles(@RequestParam(name = "file") MultipartFile[] files, HttpServletRequest request, String caseId) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean flag = false;



        String filePath = "/usr/uploadCaseFiles" + File.separator + caseId;

        for (MultipartFile file : files
                ) {
            if (file.isEmpty()) {
                map.put("failMsg", "未选中任何文件");
                continue;
            } else {
                File dest = new File(filePath + File.separator + file.getOriginalFilename());
                if (!dest.getParentFile().isDirectory()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(dest);
                    flag = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                map.put("flag", flag);
            }
        }
        return map;
    }

    /**
     * 文件下载
     *
     * @param caseId
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/downLoad")
    public ResponseEntity<byte[]> downLoad(String caseId, HttpServletRequest request) throws IOException {
        String filePath = "/usr/uploadCaseFiles" + File.separator + caseId;
        File file = new File(filePath);
        File[] files = file.listFiles();
        List<String> fileNameList = new ArrayList<String>();
        for (File fil : files
                ) {
            fileNameList.add(fil.getName());
        }
        String resourceName = caseId + ".zip";

        File file1 = new File("F:/file/" + resourceName);
        if(!file1.getParentFile().isDirectory()){
            file1.getParentFile().mkdirs();
        }
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("F:/file/" + resourceName));


        InputStream input = null;
        for (String str : fileNameList
                ) {
            String name = filePath + File.separator + str;
            System.out.println(name);
            input = new FileInputStream(name);
            zipOutputStream.putNextEntry(new ZipEntry(str));
            int temp = 0;
            while ((temp = input.read()) != -1) {
                zipOutputStream.write(temp);
            }
            input.close();
        }
        zipOutputStream.close();





        HttpHeaders headers = new HttpHeaders();
        String fileName = new String(resourceName.getBytes("utf-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file1), headers, HttpStatus.CREATED);
    }


    @RequestMapping("/isUpload")
    public Boolean isUpdate(String caseId) {
        boolean flag = false;



        String filePath = "/usr/uploadCaseFiles" + File.separator + caseId;

        File file = new File(filePath);
        if (file.isDirectory()) {
            flag = true;
        }
        return flag;
    }

}
